//
//  RTNetWroking.m
//  RtMart
//
//  Created by 福利购Mac on 16/12/2.
//  Copyright © 2016年 JASON. All rights reserved.
//

#import "RTNetWroking.h"
#import "RTCacheConstant.h"
#import "RTCacheTool.h"
#import "TokenManager.h"
#import <AFNetworking.h>
@implementation RTCache

@end



@implementation RTNetWroking
+ (NSUInteger)getSize;{
    NSUInteger size = [RTCacheTool getSize];
    NSLog(@"缓存大小为: %lu",(unsigned long)size);
    return [RTCacheTool getSize];
}
//清空缓存
+ (void)clearCache;{
        [RTCacheTool clearCache];
}

//单例
+ (instancetype)shareNetWorking{
    static id instance;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        
        instance = [[self alloc]init];
    });
    return instance;
}

/**上传多张图片*/
-(void)upLoadMultiFileWithURL:(NSString *)url parameters:(NSDictionary *)dict imageArray:(NSArray<UIImage *> *)imageArr successBlock:(void(^)(id responseObject))sucess imageNames:(void(^)(NSString *imageStr))imageNamesBlcok faildBlock:(void(^)(NSError *error))faild;{
    //AFNetworking请求
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    //申明请求的数据是json类型
    manager.requestSerializer=[AFJSONRequestSerializer serializer];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html", nil];
    NSString *baseUrl = BaseUrl;//自己定义一宏,作为基地址
    NSString *requestUrlStr = [NSString stringWithFormat:@"%@%@",baseUrl,url];
    [manager POST:requestUrlStr parameters:dict constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        NSInteger imgCount = 0;
        for (UIImage *image in imageArr) {
            NSData *data = UIImageJPEGRepresentation(image, 0.5);
            NSString *name = [NSString stringWithFormat:@"return%ld",(long)imgCount];
            NSString *fileName = [NSString stringWithFormat:@"return%ld.jpeg",(long)imgCount];
            [formData appendPartWithFileData:data name:name fileName:fileName mimeType:@"image/jpeg"];
            imgCount++;
        }
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [SVProgressHUD dismiss];
         if (sucess) {
            sucess (responseObject);
        }
     } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [SVProgressHUD dismiss];
        if (faild) {
            faild(error);
        }
    }];
}

/**上传单张图片*/
-(void)upLoadFileWithURL:(NSString *)url parameters:(NSDictionary *)dict image:(UIImage *)image successBlock:(void(^)(id responseObject))sucess imageUrl:(void(^)(NSString *url))urlBlock faildBlock:(void(^)(NSError *error))faild;{
    NSData *data = UIImageJPEGRepresentation(image, 0.5);
    //AFNetworking请求
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    //申明请求的数据是json类型
    manager.requestSerializer=[AFJSONRequestSerializer serializer];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html", nil];
    NSString *baseUrl = BaseUrl;//这里自己定义一个宏,作为基地址
    NSString *requestUrlStr = [NSString stringWithFormat:@"%@%@",baseUrl,url];
     [manager POST:requestUrlStr parameters:dict constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
        [formData appendPartWithFileData:data name:@"file" fileName:@"bill.jpeg" mimeType:@"image/jpeg"];
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [SVProgressHUD dismiss];
        if (sucess) {
            sucess(responseObject);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [SVProgressHUD dismiss];
        if (faild) {
            faild(error);
        }
    }];
}

/**普通的post请求*/
- (void)postRequestWithURL:(NSString *)url parameters:(NSDictionary *)params successBlock:(void(^)(id  responseObject))success faildBlock:(void(^)(NSError *error))faild;{
    [RTNetWroking post:url params:params cacheType:RTCacheTypeReloadIgnoringLocalCacheData success:success failure:faild];
    
}
/**post请求,可以设置缓存*/
- (void)postRequestWithURL:(NSString *)url params:(NSDictionary *)params cacheType:(NetWorkingCacheType)cacheType success:(void (^)(id responseObject))success failure:(void (^)(NSError *error))failure;{
    [RTNetWroking post:url params:params cacheType:cacheType success:success failure:failure];
    
}



//post请求
+ (void)post:(NSString *)url params:(NSDictionary *)params cacheType:(NetWorkingCacheType)cacheType success:(void(^)(id  responseObject))success failure:(void (^)(NSError *))failure{
    AFHTTPSessionManager *sessionManager = [RTNetWroking sessionManager];
    
 
    NSString *httpStr = [[BaseUrl stringByAppendingString:url] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

    [sessionManager POST:httpStr parameters:params progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        
     
        if (success) {
            
            if (cacheType == 1) {
                [SVProgressHUD dismiss];
            }
              NSMutableDictionary *dic = [(NSDictionary *)responseObject mutableCopy];

            if (!dic){
                NSString *string = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
                NSLog(@"result error = %@",string);
                return;
            }
            NSData *data = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:nil];
            success(dic);
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        if (cacheType == 1) {
            [SVProgressHUD dismiss];
        }
        
        if (failure) {
            failure(error);
        }
    }];
}

//Json post请求
- (void)jsonPost:(NSString *)url params:(NSDictionary *)params cacheType:(NetWorkingCacheType)cacheType success:(void(^)(id  responseObject))success failure:(void (^)(NSError *))failure{
    //AFNetworking请求
    AFHTTPSessionManager *sessionManager = [AFHTTPSessionManager manager];
    sessionManager.responseSerializer = [AFJSONResponseSerializer serializer];
    //申明请求的数据是json类型
    sessionManager.requestSerializer=[AFJSONRequestSerializer serializer];
    sessionManager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html", nil];
    NSString *httpStr = [[BaseUrl stringByAppendingString:url] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    //缓存数据的文件名 data。
    RTCache *cache = [RTNetWroking getCache:cacheType url:url params:params success:success];
    NSString *fileName = cache.fileName;
    if (cache.result) return;
    [sessionManager POST:httpStr parameters:params progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {

         
        
        

        if (success) {
            
            if (cacheType == 1) {
                [SVProgressHUD dismiss];
            }
            
//            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers | NSJSONReadingMutableLeaves error:nil];
            NSMutableDictionary *dic = [(NSDictionary *)responseObject mutableCopy];

            if (!dic){
                NSString *string = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
                NSLog(@"result error = %@",string);
                return;
            }
            
            NSData *data = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:nil];
            [RTCacheTool cacheForData:data fileName:fileName];
            success(dic);
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        if (cacheType == 1) {
            [SVProgressHUD dismiss];
        }
        
        if (failure) {
            failure(error);
        }
    }];
}

/**get请求,可以设置缓存.*/
- (void)getRequestWithURL:(NSString *)url params:(NSDictionary *)params cacheType:(NetWorkingCacheType)cacheType success:(void (^)(id responseObject))success failure:(void (^)(NSError * error))failure;{
    AFHTTPSessionManager *sessionManager = [RTNetWroking sessionManager];
    NSString *httpStr = [[BaseUrl stringByAppendingString:url] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    //缓存数据的文件名 data
//    RTCache *cache = [RTNetWroking getCache:cacheType url:url params:params success:success];
//    NSString *fileName = cache.fileName;
//    if (cache.result) return;
     [sessionManager GET:httpStr parameters:params progress:^(NSProgress * _Nonnull downloadProgress) {
        //NSLog(@"%lld", downloadProgress.totalUnitCount);
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        //缓存数据
    //    NSData *data = [NSJSONSerialization dataWithJSONObject:responseObject options:NSJSONWritingPrettyPrinted error:nil];
        
        NSMutableDictionary *dic = [(NSDictionary *)responseObject mutableCopy];
 //      [RTCacheTool cacheForData:data fileName:fileName];
        success(dic);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        if (failure) {
            failure(error);
        }
        
    }];
 }

//普通get请求
-(void)getRequestWithURL:(NSString *)url parameters:(NSDictionary *)dict successBlock:(void(^)(id  responseObject))success faildBlock:(void(^)(NSError *error))faild;{
    AFHTTPSessionManager *sessionManager = [RTNetWroking sessionManager];
    NSString *httpStr = [[BaseUrl stringByAppendingString:url] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
//    //缓存数据的文件名 data
    RTCache *cache = [RTNetWroking getCache:RTCacheTypeReloadIgnoringLocalCacheData url:url params:dict success:success];
    NSString *fileName = cache.fileName;
    if (cache.result) return;
    [sessionManager GET:httpStr parameters:dict progress:^(NSProgress * _Nonnull downloadProgress) {
        NSLog(@"%lld", downloadProgress.totalUnitCount);
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (success) {
            //缓存数据
            NSData *data = [NSJSONSerialization dataWithJSONObject:responseObject options:NSJSONWritingPrettyPrinted error:nil];
            [RTCacheTool cacheForData:data fileName:fileName];
            success(responseObject);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        if (faild) {
            faild(error);
        }
    }];
}


- (void)postStrRequestWithURL:(NSString *)url parameters:(NSDictionary *)params successBlock:(void(^)(id  responseObject))success faildBlock:(void(^)(NSError *error))faild{
    AFHTTPSessionManager *sessionManager = [RTNetWroking sessionManager];
    NSString *httpStr = [[BaseUrl stringByAppendingString:url] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [sessionManager  POST:httpStr parameters:params progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (success) {
            
            success(responseObject);
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (faild) {
            faild(error);
        }
        
    }];
    
}


+ (RTCache *)getCache:(NetWorkingCacheType)cacheType url:(NSString *)url params:(NSDictionary *)params success:(void (^)(NSDictionary *))success
{
    //缓存数据的文件名
    NSString *fileName = [self fileName:url params:params];
    NSData *data = [RTCacheTool getCacheFileName:fileName];
    
    RTCache *cache = [[RTCache alloc] init];
    cache.fileName = fileName;
    
    if (data.length) {
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
        if (cacheType == RTCacheTypeReloadIgnoringLocalCacheData) {//忽略缓存，重新请求
            
        } else if (cacheType == RTCacheTypeReturnCacheDataDontLoad) {//有缓存就用缓存，没有缓存就不发请求，当做请求出错处理（用于离线模式）
            
        } else if (cacheType == RTCacheTypeReturnCacheDataElseLoad) {//有缓存就用缓存，没有缓存就重新请求(用于数据不变时)
            if (success) {
                success(dict);
            }
            cache.result = YES;
            
        } else if (cacheType == RTCacheTypeReturnCacheDataThenLoad) {///有缓存就先返回缓存，同步请求数据
            if (success) {
                success(dict);
            }
        } else if (cacheType == RTCacheTypeReturnCacheDataExpireThenLoad) {//有缓存 判断是否过期了没有 没有就返回缓存
            //判断是否过期
            if (![RTCacheTool isExpire:fileName]) {
                if (success) {
                    success(dict);
                }
                cache.result = YES;
            }
        }
    }
    return cache;
}

+ (NSString *)fileName:(NSString *)url params:(NSDictionary *)params
{
    NSMutableString *mStr = [NSMutableString stringWithString:url];
    if (params != nil) {
        NSData *data = [NSJSONSerialization dataWithJSONObject:params options:NSJSONWritingPrettyPrinted error:nil];
        NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        [mStr appendString:str];
    }
    return mStr;
}

#pragma mark 设置AFN请求sessionManager
//设置AFN请求对象
+(AFHTTPSessionManager *)sessionManager
{
    AFHTTPSessionManager *sessionManager = [AFHTTPSessionManager manager];
    sessionManager.responseSerializer = [AFHTTPResponseSerializer serializer];
    //设置接受的类型
   sessionManager.responseSerializer = [AFJSONResponseSerializer serializer];
    //申明请求的数据是json类型
    sessionManager.requestSerializer=[AFJSONRequestSerializer serializer];
    sessionManager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html", nil];
    //设置请求超时
    sessionManager.requestSerializer.timeoutInterval = 30;
    //设置请求头  根据项目设置
//      [sessionManager.requestSerializer setValue:@"PHPSESSID=4c7k6slnd0jh1pecfd597cli46; user_key=3f92BN6%2FvOaDY0zZe8C3R8kZayu3g1p97w3JxTO1" forHTTPHeaderField:@"Cookie"];
    //设置请求头  根据项目设置
    [sessionManager.requestSerializer setValue:[TokenManager getToken] forHTTPHeaderField:@"X-Access-Token"];
//    [sessionManager.requestSerializer setValue:@"ios" forHTTPHeaderField:@"type"];
//    [sessionManager.requestSerializer setValue:[Config ShardInstance].lat forHTTPHeaderField:@"lat"];
//    [sessionManager.requestSerializer setValue:[Config ShardInstance].lng forHTTPHeaderField:@"lng"];
//    NSString *string =  [[NSUserDefaults standardUserDefaults] objectForKey:@"imei"];
//    if (string) {
//        [sessionManager.requestSerializer setValue:string forHTTPHeaderField:@"HTTP_IMEI"];
//    }
    return sessionManager;
}

@end


